import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getCarbonDataApi } from '@/api/carbon'
import { calculateCompare } from '@/utils/calculateCompare'

export const useCarbonStore = defineStore('carbon', () => {
    // 状态定义
    const carbonData = ref([])
    const lastCarbonData = ref([])

    // 工具函数：计算单个能源类型的年度总量
    const calculateYearlyTotal = (data, type) => {
        return data.reduce((acc, cur) => {
            const value = cur.usage[type]
            return acc + (value === null || value === undefined ? 0 : Number(value))
        }, 0)
    }

    // 工具函数：计算所有能源类型的总和
    const calculateTotalUsage = (item) => {
        return Object.values(item.usage).reduce((acc, cur) => {
            const value = cur === null || cur === undefined ? 0 : Number(cur)
            return acc + value
        }, 0)
    }

    // 计算属性：统计各项指标
    const carbonStatistics = computed(() => {
        const currentYear = {
            water: calculateYearlyTotal(carbonData.value, 'water'),
            elec: calculateYearlyTotal(carbonData.value, 'elec'),
            gas: calculateYearlyTotal(carbonData.value, 'gas'),
            oil: calculateYearlyTotal(carbonData.value, 'oil'),
            heat: calculateYearlyTotal(carbonData.value, 'heat'),
        }

        const lastYear = {
            water: calculateYearlyTotal(lastCarbonData.value, 'water'),
            elec: calculateYearlyTotal(lastCarbonData.value, 'elec'),
            gas: calculateYearlyTotal(lastCarbonData.value, 'gas'),
            oil: calculateYearlyTotal(lastCarbonData.value, 'oil'),
            heat: calculateYearlyTotal(lastCarbonData.value, 'heat'),
        }

        // 计算总量
        const yearlyTotal = Object.values(currentYear).reduce((acc, cur) => acc + cur, 0)
        const lastYearTotal = Object.values(lastYear).reduce((acc, cur) => acc + cur, 0)


        return {
            // 当年各能源类型用量
            currentYear,
            // 上年各能源类型用量
            lastYear,
            // 年度总量
            yearlyTotal,
            lastYearTotal,
            // 同比增长率
            growthRates: {
                water: calculateCompare(currentYear.water, lastYear.water),
                elec: calculateCompare(currentYear.elec, lastYear.elec),
                gas: calculateCompare(currentYear.gas, lastYear.gas),
                oil: calculateCompare(currentYear.oil, lastYear.oil),
                heat: calculateCompare(currentYear.heat, lastYear.heat),
                total: calculateCompare(yearlyTotal, lastYearTotal)
            },
            // 月度数据
            monthlyData: carbonData.value.map((item, index) => ({
                startTime: item.start_time,
                endTime: item.end_time,
                usage: item.usage,
                total: calculateTotalUsage(item),
                lastYearTotal: lastCarbonData.value[index] ?
                    calculateTotalUsage(lastCarbonData.value[index]) : 0
            }))
        }
    })

    // 获取当年数据
    async function fetchCarbonData(params) {
        try {
            const res = await getCarbonDataApi(params)
            carbonData.value = res.data
        } catch (error) {
            console.error('Failed to fetch current year carbon data:', error)
            throw error
        }
    }

    // 获取上年数据
    async function fetchLastCarbonData(params) {
        try {
            const res = await getCarbonDataApi(params)
            lastCarbonData.value = res.data
        } catch (error) {
            console.error('Failed to fetch last year carbon data:', error)
            throw error
        }
    }

    // 暴露接口
    return {
        carbonData,
        lastCarbonData,
        carbonStatistics,
        fetchCarbonData,
        fetchLastCarbonData
    }
})